/**
 * 该组件为泰山2期所有Table。由于走一个接口，所以获取数据接口写到了一起。
 */
import React, {useCallback, useState, useEffect} from 'react';
import {Table} from 'antd';
import {Link} from 'react-router-dom';
import {usePersistFn} from 'ahooks';
import {roomMessageMap} from '~/page/liveMonitor/config.js';
import {getTable} from '~/service/liveMonitor';
import './index.styl';
import {SortLabelToValue} from '../../config';

const rowName = '直播间号';
export default ({
    searchParams,
    otherColumns = '',
    rowKey,
    title,
    className = '',
    size = 'default',
    scroll = {
        x: '100%',
        y: '',
    },
    loading = true,
    // 对于一些特殊的表格，需要每个单元格设定宽度
    cellWidth = [],
    setLoading = () => {},
    setSortInfo = () => {},
    // 是否下载
    setBtnShow = () => {},
}) => {

    const [dataSource, setDataSource] = useState([]);
    const [columns, setColumns] = useState([]);
    const {dashBoardId, unitId} = roomMessageMap.get(title);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 20,
        total: 0,
    });

    const getTableList = usePersistFn(
        async (params, dashBoardId, otherColumns, unitId, pager, sorter) => {
            const {pageSize, current, total} = pager;
            const resultParams = {
                dimensionAndValues: params,
                pager: {
                    pageSize,
                    pageNum: current,
                    count: total,
                },
                dashBoardList: [
                    {
                        dashBoardName: dashBoardId,
                        dashBoardId,
                    }
                ],
            };
            if (sorter?.column) {
                resultParams.orderOptions = [
                    {
                        fieldId: sorter?.column?.fieldId,
                        name: sorter?.column?.dataIndex,
                        columnName: sorter?.column?.key,
                        fieldType: '',
                        sortRule: SortLabelToValue[sorter.order],
                    }
                ];
            }
            setLoading(true);
            const res = await getTable(resultParams);
            if (res?.code === 0 && res?.data) {
                const {
                    data,
                    pager: pages
                } = res;

                let columnData = [];
                let tableData = [];
                if (data && data[dashBoardId] && data[dashBoardId][unitId]) {
                    columnData = data[dashBoardId][unitId]?.columnList || [];
                    tableData = data[dashBoardId][unitId]?.value || [];
                }
                const columnResult = columnData?.map((item, index) => {
                    const column = {
                        key: item.id,
                        dataIndex: item.name,
                        title: item.name,
                        fieldId: item.fieldId,
                        width: cellWidth[index] || '',
                        sortOrder: sorter?.columnKey === item.id && sorter.order,
                        render(ele) {
                            if (item.name === rowName) {
                                return <Link to={`/liveMonitor/detail/${ele}`}>{ele}</Link>;
                            }
                            return ele || '-';
                        }
                    };
                    if (item?.fieldType !== 1) {
                        column.sorter = true;
                    }
                    return column;
                }) || [];
                if (typeof otherColumns === 'function' && columnResult?.length > 0) {
                    columnResult?.push(otherColumns(columnResult[0]?.dataIndex));
                }
                setColumns(columnResult);
                setDataSource(tableData);
                const {pageSize, pageNum, count} = pages;
                setPagination({
                    current: pageNum,
                    pageSize,
                    total: count
                });
                // 给下载的button设置是否显示
                if (tableData?.length > 0) {
                    setBtnShow(true);
                }
                else {
                    setBtnShow(false);
                }
                setLoading(false);
            }
        }
    );

    useEffect(() => {
        if (searchParams.length > 0) {
            const pager = {
                current: 1,
                pageSize: 20,
            };
            getTableList(searchParams, dashBoardId, otherColumns, unitId, pager);
        }
    }, [searchParams, dashBoardId, otherColumns, unitId, getTableList]);

    const handleTableChange = useCallback((pager, _, sorter) => {
        setSortInfo(sorter);
        getTableList(searchParams, dashBoardId, otherColumns, unitId, pager, sorter);
    }, [
        getTableList,
        searchParams,
        dashBoardId,
        otherColumns,
        unitId,
        setSortInfo
    ]);

    return (
        <Table
            columns={columns}
            dataSource={dataSource}
            size={size}
            loading={loading}
            className={`${className} liveMonitor-common-table`}
            rowKey={rowKey}
            onChange={handleTableChange}
            pagination={{
                ...pagination,
                showSizeChanger: true,
                showQuickJumper: true
            }}
            scroll={scroll}
        />
    );
};
